<?php
namespace System\Exceptions;

use System\Core\Request;
use System\Core\Response;
use System\Core\Config;

class Handler {
    public function report(\Throwable $e) {
        // 记录异常日志
        log_error($e->getMessage(), [
            'exception' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString()
        ]);
        
        // 如果是严重错误，记录到紧急日志
        if ($e instanceof \Error || $e instanceof \RuntimeException) {
            log_critical('Critical error: ' . $e->getMessage(), [
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
        }
    }

    public function render(Request $request, \Throwable $e) {
        $debug = Config::get('APP_DEBUG', false);
        
        if ($request->expectsJson()) {
            return $this->renderJsonResponse($e, $debug);
        }
        
        return $this->renderHtmlResponse($e, $debug);
    }

    protected function renderJsonResponse(\Throwable $e, $debug) {
        $data = [
            'error' => 'Internal Server Error',
            'message' => $e->getMessage()
        ];
        
        if ($debug) {
            $data['exception'] = get_class($e);
            $data['file'] = $e->getFile();
            $data['line'] = $e->getLine();
            $data['trace'] = $e->getTrace();
        }
        
        return Response::json($data, 500);
    }

    protected function renderHtmlResponse(\Throwable $e, $debug) {
        if ($debug) {
            $content = "<h1>500 Internal Server Error</h1>";
            $content .= "<h2>{$e->getMessage()}</h2>";
            $content .= "<p><strong>Exception:</strong> " . get_class($e) . "</p>";
            $content .= "<p><strong>File:</strong> {$e->getFile()} [{$e->getLine()}]</p>";
            $content .= "<pre>{$e->getTraceAsString()}</pre>";
        } else {
            $content = "<h1>500 Internal Server Error</h1>";
            $content .= "<p>Please contact the administrator.</p>";
        }
        
        return new Response($content, 500);
    }
}